<template>
  <div>
    <nav-header :headerTitle="'编辑文章'" :navBgColor="'#fff'" :headerNext="'下一步'" @tap2next="tap2next"></nav-header>
    <div class="nav-height"></div>
    <div class="article-edit" ref="articleedit">
      <input class="form-title" type="text" placeholder="请输入标题，字数限制为60字" v-model="title" />
      <div class="form-content-box" id="formContentWrap">
        <edit-div
          v-model="content"
          @focusContent="focusContent"
          @blurContent="blurContent"
          ref="formContent"
        ></edit-div>
        <p class="form-contentplaceholder" v-if="isShowPlaceholder">请输入正文</p>
      </div>
      <div class="height95"></div>
      <div id="articleEditFooter" class="article-edit-footer clearfix">
        <div class="edit-footer-box right" @click.stop="chooseVedio">
          <img class src="@/assets/images/edit_video.png" alt />
          <span>视频</span>
          <!-- <input type="file" name="video" id accept="video/*" capture="camcorder" multiple /> -->
        </div>
        <div class="edit-footer-box right" @click.stop="choosePhotograph">
          <img class src="@/assets/images/edit_camera.png" alt />
          <span>拍照</span>
          <!-- <input type="file" name="camera" id accept="image/*" capture="camera" multiple /> -->
        </div>
        <div class="edit-footer-box right" @click.stop="chooseAlbum">
          <img class src="@/assets/images/edit_pic.png" alt />
          <span>相册</span>
          <!-- <input type="file" name="file" id /> -->
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Vue from "vue" 
import navHeader from "@/components/NavHeader" 
import editDiv from "@/components/DivContentEditable"  
import mixins from "@/utils/mixin" 
import { Toast } from "vant" 
Vue.use(Toast);
import defaultImg from "@/assets/images/image_default.png";
export default {
  name: "articleCreate",
  mixins: [mixins],
  components: {
    navHeader,
    editDiv
  },
  data() {
    return {
      isShowPlaceholder: true,
      title: "",
      content: "",
      vedioPoster: ""
    };
  },
  watch: {
    title(){
      if(this.title.length >60){
        this.title = this.title.substring(0,60)
      }
    }
  },
  mounted() {
    this.$setgoindex() ;
    window.localStorage.uniqueId = this.$route.query.uniqueId;
    console.log(window.localStorage.uniqueId);
    if (window.sessionStorage.articleContent) {
      if (window.sessionStorage.articleContent.length > 0) {
        this.isShowPlaceholder = false;
        this.content = window.sessionStorage.articleContent;
        this.title = window.sessionStorage.articleTitle;
      }
    } else {
      this.content = " ";
    }
  },
  methods: {
    // 下一步
    tap2next() {
      // eslint-disable-line
      $(".goon").remove();  
      if (this.title.length <= 0) {
        Toast.fail("请输入标题！");
        return false;
      }
      if (this.content.length <= 0 || this.content == " ") {
        Toast.fail("请输入文章内容！");
        return false;
      }
      let _articleThumbnailsUrl;
      let imgElement = window.document.getElementById("formContentWrap").getElementsByTagName("img");
      if (imgElement.length > 0) {
        _articleThumbnailsUrl = imgElement[0].src;
      } else if (this.vedioPoster.length > 0) {
        _articleThumbnailsUrl = this.vedioPoster;
      }  
      this.content = this.content.replace(/\<p class=[\'|\"]goon[\'|\"] style=[\'|\"]width:100%\;[\'|\"]>继续写...\<\/p\>/g, ' ') ; 
      let sendData = {
        uniqueId: window.localStorage.uniqueId,
        articleTitle: this.title,
        articleContent: `<div>${this.content}</div>`,
        articleSource: 3,
        articleThumbnailsUrl: _articleThumbnailsUrl
      };
      this.$http.post("article/createArticleInfo", sendData).then(
        res => {
          window.sessionStorage.articleContent = this.content;
          window.sessionStorage.articleTitle = this.title;
          this.$router.push({
            path: "/adIndex/articleDetail",
            query: {
              articleId: res.data.articleId,
              articleTitle: this.title,
              shareUniqueId: window.localStorage.uniqueId
            }
          });
        },
        err => {
          console.log(err);
        }
      );
    },
    focusContent() { 
      this.isShowPlaceholder = false;
      // eslint-disable-line
      $(".goon").remove();  
      setTimeout(() => {
        let $articleEditFooter = window.document.getElementById("articleEditFooter");
        $articleEditFooter.scrollIntoView();
      }, 500);
    },
    blurContent() { 
      // let formContent = this.$refs.formContent.innerText;
      // eslint-disable-line
      $(".goon").remove();  
      let formContent = this.content;
      console.log(formContent);
      if (formContent.length <= 0 || formContent == " ") {
        this.isShowPlaceholder = true;
      } else {
        this.isShowPlaceholder = false;
      }
    },
    changeContent(e) {
      this.content = e.target.innerHTML;
      console.log("Text: %o", this.content);
    },
    // 选择视频
    chooseVedio() { 
      this.content = this.content.replace(/\<p class=[\'|\"]goon[\'|\"] style=[\'|\"]width:100%\;[\'|\"]>继续写...\<\/p\>/g, ' ') ; 
      let parmas = {
        sourceType: ["video"], //文章视频
        method: "articleContentVideo"
      };
      this.isShowPlaceholder = false;
      this.$bridge.callHandler("chooseImages", parmas, res => {
        this.isShowPlaceholder = false;
        if (res && res.length > 0) {
          let _vedio = res.split(",");
          this.vedioPoster = _vedio[1];
          this.content += `<video src="${_vedio[0]}" controls="controls" poster="${_vedio[1]}"  preload="auto">
            您的浏览器不支持 video 标签。
            </video><p class='goon' style='width:100%;'>继续写...</p><p style='width:100%;height:20px;'></p>`;
          // 插入成功，滚动页面底部
          this.$nextTick(function() {
            setTimeout(() => { 
              window.document.body.scrollTop = 2000000 // 滚动高度
            }, 600);
          }); 
        }
      });
    },
    // 选择拍照
    choosePhotograph() { 
      this.content = this.content.replace(/\<p class=[\'|\"]goon[\'|\"] style=[\'|\"]width:100%\;[\'|\"]>继续写...\<\/p\>/g, ' ') ;  
      let parmas = {
        maxCount: 1, //选择相册的最大数，若是相机拍照则只能为1
        sourceType: ["camera"], //相册&&拍照，可选其一
        method: "articleContentImg"
      };  
      this.$bridge.callHandler("chooseImages", parmas, res => {
        this.isShowPlaceholder = false;
        if (res && res.length > 0) {
          let imagesArr = res.split(",");
          this.content += `<img src="${imagesArr[0]}" alt /><p class="goon" style='width:100%;'>继续写...</p><p style='width:100%;height:20px;'></p>`; 
          // 插入成功，滚动页面底部
          this.$nextTick(function() {
            setTimeout(() => { 
              window.document.body.scrollTop = 2000000 // 滚动高度
            }, 600);
          });
        }
      });
    },
    // 选择相册
    chooseAlbum() { 
      this.content = this.content.replace(/\<p class=[\'|\"]goon[\'|\"] style=[\'|\"]width:100%\;[\'|\"]>继续写...\<\/p\>/g, ' ') ; 
      let parmas = {
        maxCount: 9, //选择相册的最大数，若是相机拍照则只能为1
        sourceType: ["album"], //相册&&拍照，可选其一
        method: "articleContentImg"
      };
      this.isShowPlaceholder = false; 
      this.$bridge.callHandler("chooseImages", parmas, res => {
        this.isShowPlaceholder = false;
        if (res && res.length > 0) {
          let imagesArr = res.split(",");
          imagesArr.forEach(element => {
            this.content += `<img src="${element}" alt onerror="this.src='${defaultImg}'"/>`;
          });
           this.content +="<p class='goon' style='width:100%;'>继续写...</p><p style='width:100%;height:20px;'></p>"
          // 插入成功，滚动页面底部
          this.$nextTick(function() {
            setTimeout(() => { 
              window.document.body.scrollTop = 2000000 // 滚动高度
            }, 600);
          });
        }
      });
    }
  }, 
};
</script>

<style scoped lang="scss">
.article-edit {
  width: 686px;
  background: #fff;
  margin: 0 auto 95px;
  .height95 {
    width: 100%;
    height: 95px;
  }
  .form-title {
    display: block;
    width: 100%;
    margin: 16px auto 0;
    padding: 16px 0;
    font-size: 40px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: #303133;
    line-height: 56px;
    border-bottom: 1px solid #ededed;
  }
  .form-content-box {
    width: 100%;
    font-size: 32px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(129, 129, 129, 1);
    line-height: 45px;
    margin: 0 auto 100px;
    position: relative;
    .form-contentplaceholder {
      position: absolute;
      top: 50px;
      left: 0;
      color: rgba(129, 129, 129, 1);
    }
  } 
  .article-edit-footer {
    width: 100%;
    height: 88px;
    background: #fff;
    border-top: 1px solid rgba(216, 208, 208, 0.24);
    box-sizing: border-box;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 99;
    .edit-footer-box {
      height: 88px;
      font-family: PingFangSC-Regular;
      font-size: 28px;
      color: #818181;
      letter-spacing: 0;
      line-height: 88px;
      margin-right: 48px;
      position: relative;
      & > img {
        width: 44px;
        position: relative;
        top: -2px;
      }
      & > span {
        margin-left: 8px;
      }
      & > input {
        width: 100%;
        height: 100%;
        opacity: 0;
        position: absolute;
        top: 0;
        left: 0;
      }
    }
  }
}
</style>
